<template>
  <div>
    <ElRow style="margin-bottom: 16px">
      <el-button v-if="hasPerms('product:config:edit')" type="primary" @click="handleAdd">新增</el-button>
    </ElRow>
    <ReTable :data="productList" :columns="productColumns" :pagination="pagination">
      <template #goodsImage="{ row }">
        <ElImage :preview-src-list="[row.goodsImage]" :preview-teleported="true" fit="cover" :src="row.goodsImage"
          alt="" style="width: 100px; height: 100px" />
      </template>
      <template #action="{ row }">
        <ElRow justify="center" align="middle">
          <ElCol v-if="hasPerms('product:config:state')" :span="6">
            <ElButton link type="primary" @click="stateChange(row)">
              {{ row.state === 0 ? "上架" : "下架" }}
            </ElButton>
          </ElCol>
          <ElCol v-if="hasPerms('product:config:edit')" :span="6">
            <ElButton link type="primary" @click="handleEdit(row)">
              编辑
            </ElButton>
          </ElCol>
        </ElRow>
      </template>
    </ReTable>
    <ElDialog v-model="dialogVisible" :close-on-click-modal="false" :title="dialogTitle" width="50%"
      :destroy-on-close="true">
      <el-form ref="ruleFormRef" style="min-width: 600px; flex: 1; margin: auto" :model="ruleForm" :rules="rules"
        label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="ruleForm.goodsName" />
        </el-form-item>
        <el-form-item label="销售价格" prop="salePrice">
          <el-input v-model="ruleForm.salePrice" type="number" />
        </el-form-item>
        <el-form-item label="划线价格" prop="originalPrice">
          <el-input v-model="ruleForm.originalPrice" type="number" />
        </el-form-item>
        <el-form-item label="商品图" prop="goodsImage">
          <el-upload ref="upload" class="avatar-uploader" :limit="1" action="/api/platform/file/upload/image"
            :with-credentials="true" :headers="{ token: getToken().token }" :on-exceed="handleExceed"
            :show-file-list="false" :auto-upload="false" @success="uploadImage" @change="submitUpload">
            <img v-if="ruleForm.goodsImage" :src="ruleForm.goodsImage" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="关联产品" prop="productId">
          <el-select v-model="ruleForm.productId" placeholder="请选择">
            <el-option v-for="item in formProductsList" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <ElButton @click="dialogVisible = false">取消</ElButton>
          <ElButton v-if="hasPerms('product:config:save')" type="primary" @click="handleConfirm">确认生成</ElButton>
        </span>
      </template>
    </ElDialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { Plus } from "@element-plus/icons-vue";
import {
  ElMessage,
  genFileId,
  UploadRawFile,
  type ComponentSize,
  type FormInstance,
  type FormRules,
  type UploadInstance,
  type UploadProps
} from "element-plus";
import ReTable from "@/components/ReTable";
import {
  getGoodsListApi,
  getGoodsListByConfigIdApi,
  createGoodsApi,
  updateGoodsApi,
  updateGoodsStatusApi
} from "@/api/product";
import { getToken, hasPerms } from "@/utils/auth";

// 表单数据
interface RuleForm {
  goodsName: string;
  salePrice: number;
  originalPrice: number;
  goodsImage: string;
  productId: number;
  id?: number;
}

const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  goodsName: "",
  salePrice: undefined,
  originalPrice: undefined,
  goodsImage: "",
  productId: undefined
});
// 显示表格
const dialogVisible = ref(false);
const dialogTitle = ref("创建商品");

// 产品列表
const formProductsList = ref([]);

// 表格数据
const productList = ref([]);
// 表格列配置
const productColumns = [
  {
    label: "商品名称",
    prop: "goodsName"
  },
  {
    label: "商品售价",
    prop: "salePrice"
  },
  {
    label: "商品原价",
    prop: "originalPrice"
  },
  {
    label: "商品图片",
    prop: "goodsImage",
    slotName: "goodsImage"
  },
  {
    label: "操作",
    prop: "action",
    slotName: "action"
  }
];
// 表格分页
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

const rules = reactive<FormRules<RuleForm>>({
  goodsName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  salePrice: [{ required: true, message: "请输入商品售价", trigger: "blur" }],
  originalPrice: [
    { required: true, message: "请输入商品原价", trigger: "blur" }
  ],
  goodsImage: [{ required: true, message: "请输入商品图片", trigger: "blur" }],
  productId: [{ required: true, message: "请输入商品ID", trigger: "blur" }]
});
// 创建商品
const handleConfirm = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      if (dialogTitle.value === "新增商品") {
        createGoodsApi({
          ...ruleForm,
          salePrice: Number(ruleForm.salePrice),
          originalPrice: Number(ruleForm.originalPrice)
        }).then(res => {
          if (res.code === 200) {
            ElMessage.success("创建成功");
            dialogVisible.value = false;
            ruleFormRef.value.resetFields();
            getGoodsList();
          } else {
            ElMessage.error(res.message);
          }
        });
      } else {
        updateGoodsApi(ruleForm.id, {
          ...ruleForm,
          salePrice: Number(ruleForm.salePrice),
          originalPrice: Number(ruleForm.originalPrice)
        }).then(res => {
          if (res.code === 200) {
            ElMessage.success("修改成功");
            dialogVisible.value = false;
            ruleFormRef.value.resetFields();
            getGoodsList();
          } else {
            ElMessage.error(res.message);
          }
        });
      }

      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 上传图片
const uploadImage = (file: any) => {
  console.log(file);
  ruleForm.goodsImage = file.data;
};

// 上传
const submitUpload = async () => {
  upload.value!.submit();
};

// 编辑商品
const handleEdit = async (row: any) => {
  dialogTitle.value = "编辑商品";
  ruleForm.goodsName = row.goodsName;
  ruleForm.salePrice = row.salePrice;
  ruleForm.originalPrice = row.originalPrice;
  ruleForm.goodsImage = row.goodsImage;
  ruleForm.productId = row.productId;
  ruleForm.id = row.id;
  dialogVisible.value = true;
};

// 上下架商品
const stateChange = async (row: any) => {
  const res = await updateGoodsStatusApi({
    id: row.id,
    state: row.state === 1 ? 0 : 1
  });
  if (res.code === 200) {
    ElMessage.success("操作成功");
    getGoodsList();
  } else {
    ElMessage.error(res.message);
  }
};

// 新增商品
const handleAdd = async () => {
  dialogTitle.value = "新增商品";
  dialogVisible.value = true;
};

// 初始化获取列表数据
onMounted(async () => {
  getGoodsList();
  const res = await getGoodsListByConfigIdApi();
  formProductsList.value = res.data;
});

// 获取商品列表
const getGoodsList = async () => {
  const { data } = await getGoodsListApi();
  if (data) {
    productList.value = [data];
    pagination.total = data.total;
  }
};
const upload = ref<UploadInstance>();
// 覆盖前一个文件
const handleExceed: UploadProps["onExceed"] = files => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
}
</style>
